package com.sita.bike.task;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.sita.bike.rest.model.Resource2;
import com.sita.bike.utils.AccountUtils;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

/**
 * Created by lijuaan zhang on 16/2/18.
 */
public class MemberAvatarListLoadTask extends AsyncTask<Void, Void, Void> {
    private List<Resource2> mResource;
    private List<String> mAvatarUrls;

    public MemberAvatarListLoadTask(List<String> avatarurls) {
        this.mAvatarUrls = avatarurls;
    }

    @Override
    protected Void doInBackground(Void... params) {

        for (int i = 0; i < mAvatarUrls.size(); i++) {
            final String mAvatarUrl = mAvatarUrls.get(i);
                Bitmap bitmap = AccountUtils.getMemberAvatar(mAvatarUrl);
                if (bitmap == null) {
                    bitmap = ImageLoader.getInstance().loadImageSync(mAvatarUrl);
                    if (bitmap == null) {
                        ImageLoader.getInstance().loadImage(mAvatarUrl, new SimpleImageLoadingListener() {
                            @Override
                            public void onLoadingComplete(String imageUri, View view,
                                                          Bitmap loadedImage) {
                                super.onLoadingComplete(imageUri, view, loadedImage);

                                //write your code here to use loadedImage
                                AccountUtils.addMemberAvatar(mAvatarUrl, loadedImage);
//                                EventBus.getDefault().post(new DrawResourceEvent(res, res.mAccount.mAccountId, loadedImage));
                            }
                        });
                    }else {
                        AccountUtils.addMemberAvatar(mAvatarUrl, bitmap);
                        Log.d("ImageLoader", "after download resource");
//                        EventBus.getDefault().post(new DrawResourceEvent(res, res.mAccount.mAccountId, bitmap));
                    }

                }

        }
        return null;
    }

    //
    public void onProgressUpdate(Void... voids) {
    }

    public InputStream getStream(String urlStr) {
        InputStream inStream = null;
        try {
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            conn.setConnectTimeout(10 * 1000);
            inStream = conn.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inStream;
    }
}
